<!--
 * @Description: useBroadcastChannel(浏览器标签间通信)
 * @Author: r_yuesheng
 * @Date: 2022-12-23 16:33:54
 * @LastEditTime: 2022-12-30 13:42:49
 * @LastEditors: r_yuesheng
-->
<template>
  <div>
    <p>
      是否支持:
      <span>{{ isSupported }}</span>
    </p>
    <p>请至少在两个选项卡中打开此页</p>
  </div>
  <div v-if="isSupported">
    <el-input v-model="message" style="width:300px"></el-input>
    <el-button type="primary" @click="postMessage" class="ml10">发送消息</el-button>

    <p v-if="receiveMsg" class="mt10">
      最新消息: {{ receiveMsg }}
    </p>
    <div class="mt10">
      <h3 class="p6">消息列表</h3>
      <div style="background:#d2e0fa">
        <div v-for="(item,index) in listMsg" :key="index" class="mt6 p6">
          <div class="fs12">{{`${item.type} | ${item.time}`}}</div>
          <div>{{item.msg}}</div>
        </div>
      </div>

    </div>
    <p v-if="error">
      错误信息: {{ error }}
    </p>
  </div>
  <div v-else>
    您的浏览器不支持广播频道Web API。
  </div>
</template>
<script>
import { reactive, toRefs, ref, watch, onMounted } from 'vue';
import { useBroadcastChannel, useNow, useDateFormat } from '@vueuse/core';
export default {
  name: '',
  props: {},
  components: {},
  setup(props, { emit }) {
    function initState() {
      return {
        message: '',
        receiveMsg: [],
        error: '',
        listMsg: [],
      };
    }
    const state = reactive(initState());
    const { isSupported, data, post, error } = useBroadcastChannel({ name: 'vueuse-demo-channel' });
    state.error = error;

    watch(data, () => {
      if (data.value) {
        state.receiveMsg = data.value;
        saveMsg(data.value, '对方');
      }
    });
    function postMessage() {
      post(state.message);
      saveMsg(state.message, '我');
    }
    function saveMsg(msg, type) {
      const currTime = useDateFormat(new Date(), 'YYYY-MM-DD HH:mm:ss  dddd');
      state.listMsg.push({ time: currTime, msg: msg, type });
    }
    return {
      ...toRefs(state),
      isSupported,
      post,
      error,
      postMessage,
    };
  },
};
</script>